import random
from time import sleep
from os import system, path
from common import show_log

import img
import setting
from img import find_pic_old, find_pic, find_pic_ex


def delay(sec: float, delay_random: float = setting.delay_random, min_sec: float = -1, max_sec: float = -1):
    """
    延时，单位秒
    :param sec: 延时秒数
    :param delay_random: 延时随机系数，范围[0-1)，0为关闭
    :param min_sec: 最短延时秒数，若小于0，则表示该项无效
    :param max_sec: 最长延时秒数，若小于0，则表示该项无效
    :return:
    """

    if 0 < delay_random < 1:
        sec = sec * random.uniform(1 - delay_random, 1 + delay_random)

    # 判断最短延时
    if min_sec > 0 and sec < min_sec:
        sec = min_sec

    # 判定最长延时
    if 0 < max_sec < sec:
        sec = max_sec

    # show_log(f'延时{sec * setting.speed}秒')

    sleep(sec * setting.speed)


def send_adb_cmd(cmd: str) -> bool:
    cmd = f'bin\\adb -s {setting.device_name} {cmd}'
    cmd_return = system(cmd)
    delay(0.5)
    if cmd_return == 0:
        return True
    else:
        return False


def capture():
    cmd_return = send_adb_cmd(
        'shell screencap -p /storage/emulated/0/Pictures/Screenshots/capture.png')
    if cmd_return:
        return path.abspath(f'{setting.pic_path}\\capture.png')
    else:
        return None


def click(x: int, y: int) -> bool:
    return send_adb_cmd(f'shell input tap {x} {y}')


def click_zone(x1: int, y1: int, x2: int, y2: int):
    """
    点击指定区域的某个随机点

    :param x1:
    :param y1:
    :param x2:
    :param y2:
    :return:
    """
    w = abs(x2 - x1)
    h = abs(y2 - y1)
    x = int(min(x1, x2) + w * random.random())
    y = int(min(y1, y2) + h * random.random())
    # show_log(f'点击区域 ({x1}, {y1}, {x2}, {y2}) → ({x}, {y})')
    click(x, y)


def click_pic_old(pic) -> bool:
    screen = capture()
    x1, y1, x2, y2, sim = find_pic_old(screen, pic)
    if sim > setting.img_threshold:
        show_log(f'[{round(sim, 4)}]找不到 {pic}')
        return False
    else:
        show_log(f'[{round(sim, 4)}]找到并点击 {pic}')
        click_zone(x1, y1, x2, y2)
        return True


def click_pic(pic, debug_mode: bool = False) -> bool:
    screen = capture()
    x1, y1, x2, y2, cent_x, cent_y = find_pic_ex(
        screen, pic, setting.img_threshold)
    if x1 == y1 == x2 == y2 == cent_x == cent_y == -1:
        if debug_mode:
            show_log(f'找不到 {pic}')
        return False
    else:
        if debug_mode:
            show_log(f'找到并点击 {pic}')
        click_zone(x1, y1, x2, y2)
        return True


def in_zone(px: int, py: int, z_x1: int, z_y1: int, z_x2: int, z_y2: int) -> bool:
    """
    判断点是否在指定区域

    :param px: 点的X坐标
    :param py: 点的Y坐标
    :param z_x1: 区域左上角的X坐标
    :param z_y1: 区域左上角的Y坐标
    :param z_x2: 区域右下角的X坐标
    :param z_y2: 区域右下角的Y坐标
    :return:
    """
    if px in range(z_x1, z_x2) and py in range(z_y1, z_y2):
        return True
    else:
        return False


def click_skip() -> bool:
    """
    点击跳过

    :return:
    """
    return click_pic('assets/skip.png')


def close_rewards():
    """
    关闭“合计获得奖励”窗口

    :return:
    """
    click_zone(580, 604, 717, 640)


def open_map():
    """
    点击“作战总揽”，打开大地图

    :return:
    """
    click_zone(1072, 642, 1257, 693)


def close_msgbox() -> bool:
    """
    关闭确认弹窗

    :return:
    """
    screen = capture()
    if find_pic(screen, 'assets/msgbox.png'):
        click_zone(714, 491, 868, 533)
        return True
    else:
        return False


def auto_fight():
    """
    自律寻敌

    :return:
    """
    click_zone(1185, 568, 1272, 594)


def find_auto_fight_button() -> bool:
    """
    是否找到自律战斗按钮
    :return:
    """
    screen = capture()
    if find_pic(screen, 'assets/overview.png'):
        return find_pic(screen, 'assets/auto_fight.png')
    else:
        return False


def is_finish_fight() -> bool:
    """
    是否结束战斗

    :return:
    """
    screen = capture()
    return find_pic(screen, 'assets/total_rewards.png')


def is_found_akashi() -> bool:
    """
    是否找到老板娘

    :return:
    """
    screen = capture()
    if find_pic(screen, 'assets/akashi_face.png'):
        return True
    else:
        return find_pic(screen, 'assets/akashi_face2.png')


def click_akashi() -> bool:
    """
    点击老板娘

    :return:
    """
    screen = capture()
    _, _, _, _, x, y = find_pic_ex(screen, 'assets/akashi_face.png')
    if x != -1 and y != -1:
        # 修正Y坐标
        y += 66
        click(x, y)
        return True

    _, _, _, _, x, y = find_pic_ex(screen, 'assets/akashi_face2.png')
    if x != -1 and y != -1:
        # 修正Y坐标
        y += 66
        click(x, y)
        return True

    return False


def shopping():
    # 进入商店
    click_zone(317, 196, 982, 576)
    delay(1)
    click_zone(739, 278, 1102, 308)
    delay(1)

    # 购买商品
    def buy_item(pic_name: str, item_name: str) -> bool:
        if click_pic(pic_name):
            show_log(f'购买{item_name}')
            delay(1)
            click_zone(714, 488, 868, 528)
            delay(1)
            click_zone(777, 127, 1200, 628)
            return True
        else:
            return False

    have_good = True

    while have_good:
        if buy_item('assets/zibi.png', '紫币') or buy_item('assets/tili1.png', '小体力箱') \
                or buy_item('assets/tili2.png', '中体力箱') or buy_item('assets/tili3.png', '大体力箱'):
            have_good = True
        else:
            have_good = False

        delay(1)

    show_log('购买结束')

    # 退出商店
    click_zone(32, 37, 78, 71)


def get_sea_area_index() -> int:
    """
    获取当前海域序号
    左(西大陆架D) = 1
    右(NA海域西南B) = 2
    :return:
    """
    screen = capture()
    # _, _, _, _, x, y = img.find_pic_ex(screen, 'assets/return_sea.png')
    # if in_zone(x, y, 398, 279, 540, 315):
    #     show_log('当前在左海域(西大陆架D)')
    #     return 1
    # elif in_zone(x, y, 400, 280, 538, 317):
    #     show_log('当前在右海域(NA海域西南B)')
    #     return 2
    # else:
    #     show_log('找不到海域')
    #     return 0
    if img.find_pic(screen, 'assets/sea_area_1.png', 0.9):
        show_log('当前在左海域(西大陆架D)')
        return 1
    elif img.find_pic(screen, 'assets/sea_area_2.png', 0.9):
        show_log('当前在右海域(NA海域西南B)')
        return 2
    else:
        show_log('找不到海域')
        return 0


def switch_sea_area() -> int:
    """
    切换作战海域

    :return:
    """
    sea_area_index = get_sea_area_index()
    if sea_area_index == 1:
        # 当前是左海域，切换到右海域
        click_zone(615, 379, 704, 553)
        delay(1)
        click_zone(398, 279, 540, 315)
    elif sea_area_index == 2:
        # 当前是右海域，切换到左海域
        click_zone(268, 421, 382, 524)
        delay(1)
        click_zone(398, 279, 540, 315)

    return sea_area_index
